package org.budo.beetl.resource.classpath;

import org.beetl.core.GroupTemplate;
import org.beetl.core.Resource;
import org.beetl.core.ResourceLoader;
import org.beetl.core.misc.BeetlUtil;
import org.springframework.core.io.ClassPathResource;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 * @see org.beetl.core.resource.ClasspathResourceLoader
 */
@Getter
@Setter
@Slf4j
public class BudoClassPathBeetlResourceLoader implements ResourceLoader {
    private String root;

    @Override
    public boolean exist(String id) {
        BudoClassPathBeetlResource resource = this.getResource(id);
        ClassPathResource classPathResource = resource.toSpringResource();
        boolean exists = classPathResource.exists();

        if (!exists) {
            log.warn("#30 Resource not exists, id=" + id + ", resource=" + resource + ", classPathResource=" + classPathResource);
        }

        return exists;
    }

    @Override
    public BudoClassPathBeetlResource getResource(String id) {
        return new BudoClassPathBeetlResource(id, this, this.getRoot());
    }

    @Override
    public boolean isModified(Resource resource) {
        return resource.isModified();
    }

    @Override
    public String getResourceId(Resource resource, String id) {
        if (null == resource) {
            return id;
        }

        String relPath = BeetlUtil.getRelPath(resource.getId(), id);
        return relPath;
    }

    @Override
    public void close() {
        log.info("#58 close, this=" + this);
    }

    @Override
    public String getInfo() {
        return "this:" + this + ", root:" + root;
    }

    @Override
    public void init(GroupTemplate groupTemplate) {
        log.info("#68 init, this=" + this);
    }
}
